package com.birth.memo.db;



import java.util.HashMap;

import com.birth.memo.util.Constants;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;



public class DataProvider extends ContentProvider {
	private static final String TAG = "DbBirthMemo";
	private static final String DATABASE_NAME ="birth_memo.db";
	private static final int DATABASE_VER =1;
	private static final String TABLE_NAME_SMS = "sms";
	private static final String TABLE_NAME_MEMO = "memo";
	
	public static final String CONTENT_TYPE_SMS = "com.birth.memo/sms";
	public static final String CONTENT_TYPE_MEMO = "com.birth.memo/memo";
	
	

	
    /** 
     * sms
     */
    private static HashMap<String, String> smsProjectionMap;
    
    /** 
     * memo
     */
    private static HashMap<String, String> memoListProjectionMap;    
 

   
    private static final int SMS = 1;
    private static final int MEMO = 3;  
    

    private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
	
    private DatabaseHelper mOpenHelper;
    
    static {       
        sUriMatcher.addURI("com.birth.memo", "sms", SMS);       
        sUriMatcher.addURI("com.birth.memo", "memo", MEMO);

        smsProjectionMap = new HashMap<String, String>();
        smsProjectionMap.put("_id", "_id");
        smsProjectionMap.put("sms", "sms");
        
        memoListProjectionMap = new HashMap<String,String>();
        memoListProjectionMap.put("_id", "_id");
        memoListProjectionMap.put("person_name","person_name");
        memoListProjectionMap.put("flag","flag");
        memoListProjectionMap.put("birth_yin", "birth_yin");
        memoListProjectionMap.put("birth_yang", "birth_yang");
        
    }	
	
   @Override
    public boolean onCreate() 
   	{
	   Log.i("DEMO","DataProvider>>>onCreate ");
	        mOpenHelper = new DatabaseHelper(getContext());
	        mOpenHelper.getWritableDatabase();
	        return true;
   	}


	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		  SQLiteDatabase db = mOpenHelper.getWritableDatabase();
	       int count = 0;
	        switch (sUriMatcher.match(uri)) {
	        case SMS:
	            count = db.delete(TABLE_NAME_SMS, where, whereArgs);
	            break;
	       
	        case MEMO:
	        	count = db.delete(TABLE_NAME_MEMO, where, whereArgs);
	        	break;	      
	        default:
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }

	        getContext().getContentResolver().notifyChange(uri, null);
	        return count;
	}

	@Override
	public String getType(Uri uri) {
		Log.i("DEMO","DataProvider>>> getType");
		  switch (sUriMatcher.match(uri)) {
	        case SMS:
	            return CONTENT_TYPE_SMS;	       
	        case MEMO:
	        	return CONTENT_TYPE_MEMO;	       
	        default:
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {		
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		long rowId = 0; 
		Uri retUri = null;
		
		switch (sUriMatcher.match(uri)) {
		case SMS:			
			db = mOpenHelper.getWritableDatabase();			
			rowId = db.insert(TABLE_NAME_SMS, null, values);
			retUri = ContentUris.withAppendedId(Constants.URI_SMS, rowId);
			break;		
		case MEMO:
			rowId = db.insert(TABLE_NAME_MEMO, null, values);
			retUri = ContentUris.withAppendedId(Constants.URI_MEMO, rowId);
			break;	
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		
		return retUri;
	}



	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		
			Log.i("DEMO", "DataProvider.query....");
		
		   SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

	        switch (sUriMatcher.match(uri)) {	       
	        case SMS:
	            qb.setTables(TABLE_NAME_SMS);
	            qb.setProjectionMap(smsProjectionMap);	            
	            break;	        
	        case MEMO:
	        	qb.setTables(TABLE_NAME_MEMO);
	        	qb.setProjectionMap(memoListProjectionMap);
	        	break;
	       
	        default:
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }

	        // If no sort order is specified use the default
	        String orderBy;
	        if (TextUtils.isEmpty(sortOrder)) {
	            orderBy = " _id desc";
	        } else {
	            orderBy = sortOrder;
	        }

	        // Get the database and run the query
	        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
	        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);

	        // Tell the cursor what uri to watch, so it knows when its source data changes
	        c.setNotificationUri(getContext().getContentResolver(), uri);
	        return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String where,
			String[] whereArgs) {
		
		  SQLiteDatabase db = mOpenHelper.getWritableDatabase();
	        int count;
	        switch (sUriMatcher.match(uri)) {
	        case MEMO:
	            count = db.update(TABLE_NAME_MEMO, values, where, whereArgs);
	            break;	      
	        default:
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }

	        getContext().getContentResolver().notifyChange(uri, null);
	        return count;
	}
	
	
	 
	 private static class DatabaseHelper extends SQLiteOpenHelper{	
			
			public DatabaseHelper(Context context) {			
				super(context, DATABASE_NAME, null, DATABASE_VER);
				Log.i(TAG,"DatabaseHelper DatabaseHelper");
			}

			@Override
			public void onCreate(SQLiteDatabase db) {			
				Log.v(TAG, "db onCreate begin------------------");
				
				StringBuffer sql = new StringBuffer();
				//短信表
				sql.append("CREATE TABLE if not exists sms(");
				sql.append("_id INTEGER PRIMARY KEY AUTOINCREMENT,");
				sql.append("sms varchar(150))");
				db.execSQL(sql.toString());
				
				//备忘表
				sql = new StringBuffer();
				sql.append("CREATE TABLE if not exists memo(");
				sql.append("_id INTEGER PRIMARY KEY AUTOINCREMENT,");
				sql.append("person_name varchar(30),");
				sql.append("flag INTEGER,");
				sql.append("birth_yin varchar(14),");
				sql.append("birth_yang varchar(14))");
				db.execSQL(sql.toString());
				
				String hsql = "INSERT INTO sms (_id, sms) VALUES ";
			    db.execSQL(hsql + "(1,'两片绿叶，饱含着它同根生的情谊；一句贺词，浓缩了我对你的祝福。愿快乐拥抱你，在这属于你的特别的一天，生日快乐！');");
			    db.execSQL(hsql + "(2,'在思念之中，我想起了你的生日。我谨用只字片语，表达对你的情怀。衷心祝愿您青春长驻，愿将一份宁静和喜悦悄悄带给您，生日快乐！');");
			    db.execSQL(hsql + "(3,'岁月总是愈来愈短，生日总是愈来愈快，友情总是愈来愈浓，我的祝福也就愈来愈深愿你的每一天都如画一样的美丽？？生日快乐！');");
			    db.execSQL(hsql + "(4,'希望我是第一个向你道“生日快乐”的朋友，愿这一年中快乐、成功！ ');");
								
			    
				Log.v(TAG, "DB init success!------------------------");
			}

			@Override
			public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
				
				  
			}
			
		}

}
